package com.shijie.newvideo;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import com.shijie.newvideo.header.HeaderAndFooterWrapperAdapter;
import com.shijie.newvideo.slide_recyclerview.SwipeMenuRecyclerView;


/**
 * 支持setEmpty的recycler view
 * @author zhangdunxiang create at 2017/6/15 21:53
 */
public class EmptySupportedRecyclerView extends SwipeMenuRecyclerView {
    private View emptyView;

    /**
     * 观察者模式  数据改变的时候调用 showEmptyView
     */
    private RecyclerView.AdapterDataObserver emptyObserver = new RecyclerView.AdapterDataObserver() {

        @Override
        public void onChanged() {
            showEmptyView();
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            showEmptyView();
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            showEmptyView();
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            showEmptyView();
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
            showEmptyView();
        }
    };

    /**
     * 控制empty试图的显示和隐藏
     */
    private void showEmptyView() {
        emptyView.setVisibility(View.GONE);
        EmptySupportedRecyclerView.this.setVisibility(View.VISIBLE);
        RecyclerView.Adapter<?> adapter = getAdapter();
        if (adapter != null && emptyView != null) {
            int count;
            // TODO: 2017/6/21 添加判断是否不计算头部数量显示空白页
            if(adapter instanceof HeaderAndFooterWrapperAdapter){
                count =( (HeaderAndFooterWrapperAdapter)adapter).getRealItemCount();
            }else{
                count = adapter.getItemCount();
            }
            if (count == 0) {
                emptyView.setVisibility(View.VISIBLE);
                EmptySupportedRecyclerView.this.setVisibility(View.GONE);
            } else {
                emptyView.setVisibility(View.GONE);
                EmptySupportedRecyclerView.this.setVisibility(View.VISIBLE);
            }
        }
    }

    public EmptySupportedRecyclerView(Context context) {
        super(context);
    }

    public EmptySupportedRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EmptySupportedRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setAdapter(RecyclerView.Adapter adapter) {
        super.setAdapter(adapter);

        if (adapter != null) {
            adapter.registerAdapterDataObserver(emptyObserver);
        }

        emptyObserver.onChanged();
    }

    public void setEmptyView(View emptyView) {
        this.emptyView = emptyView;
    }

    public View getEmptyView() {
        return emptyView;
    }
}